import React, { useEffect, useState, useRef } from 'react';
import { Card, Typography, Statistic, Row, Col, Button, Modal, message } from 'antd';
import { UserOutlined, CheckCircleOutlined, ClockCircleOutlined, CameraOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import FaceCapture from '../../components/FaceCapture';
import { signInAPI, authAPI } from '../../services/api';
import { getUserInfo } from '../../store/slices/authSlice';
import './styles.scss';

const { Title, Paragraph } = Typography;

const Dashboard = () => {
  const dispatch = useDispatch();
  const { user } = useSelector(state => state.auth);
  const [stats, setStats] = useState({
    totalTasks: 0,
    completedTasks: 0,
    pendingTasks: 0
  });
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [faceImage, setFaceImage] = useState(null);
  const [faceRegistered, setFaceRegistered] = useState(user?.has_face || false);
  const [error, setError] = useState(null);
  
  // 使用ref标记是否已经发起了请求
  const userInfoRequested = useRef(false);
  const dataFetched = useRef(false);
  
  // 在组件加载时获取最新的用户信息 - 添加防止无限循环的保护
  useEffect(() => {
    // 只在组件首次渲染时请求一次用户信息
    if (!userInfoRequested.current) {
      userInfoRequested.current = true;
      console.log('Dashboard组件挂载，获取用户信息');
      dispatch(getUserInfo());
    }
    
    // 组件卸载时重置标记
    return () => {
      userInfoRequested.current = false;
    };
  }, []);
  
  // 当用户信息更新时，更新人脸注册状态
  useEffect(() => {
    if (user) {
      console.log("用户信息更新:", user.name, "has_face:", user.has_face);
      setFaceRegistered(user.has_face || false);
    }
  }, [user?.id, user?.has_face]); // 只在用户ID或人脸状态变化时更新
  
  useEffect(() => {
    // 只在组件首次渲染时获取数据
    if (!dataFetched.current) {
      dataFetched.current = true;
      fetchData();
    }
    
    // 组件卸载时重置标记
    return () => {
      dataFetched.current = false;
    };
  }, []);
  
  // 获取待签到任务和历史签到数据
  const fetchData = async () => {
    setLoading(true);
    setError(null);
    
    try {
      console.log('开始获取签到任务和历史数据...');
      
      // 获取待签到任务
      let pendingTasks = [];
      try {
        const pendingRes = await signInAPI.getPendingTasks();
        console.log('获取到的待签到任务:', pendingRes);
        
        // 处理不同格式的响应
        if (pendingRes.data?.data) {
          pendingTasks = Array.isArray(pendingRes.data.data) ? pendingRes.data.data : [pendingRes.data.data];
        } else if (pendingRes.data?.tasks) {
          // 兼容Go后端可能的不同响应格式
          pendingTasks = Array.isArray(pendingRes.data.tasks) ? pendingRes.data.tasks : [pendingRes.data.tasks];
        } else {
          pendingTasks = [];
        }
        
        console.log('处理后的待签到任务:', pendingTasks);
      } catch (err) {
        console.error('获取待签到任务失败:', err);
        message.error('获取待签到任务失败，请稍后重试');
        pendingTasks = [];
      }
      
      // 获取签到历史
      let historyList = [];
      try {
        const historyRes = await signInAPI.getHistory();
        console.log('获取到的签到历史:', historyRes);
        
        // 处理不同格式的响应
        if (historyRes.data?.data) {
          historyList = Array.isArray(historyRes.data.data) ? historyRes.data.data : [historyRes.data.data];
        } else if (historyRes.data?.records) {
          // 兼容Go后端可能的不同响应格式
          historyList = Array.isArray(historyRes.data.records) ? historyRes.data.records : [historyRes.data.records];
        } else {
          historyList = [];
        }
        
        console.log('处理后的签到历史:', historyList);
      } catch (err) {
        console.error('获取签到历史失败:', err);
        message.error('获取签到历史失败，请稍后重试');
        historyList = [];
      }
      
      // 计算统计数据
      setStats({
        totalTasks: pendingTasks.length + historyList.length,
        completedTasks: historyList.length,
        pendingTasks: pendingTasks.length
      });
      
      console.log('数据获取完成');
    } catch (error) {
      console.error('获取数据失败:', error);
      setError('获取数据失败，请稍后重试');
      message.error('获取数据失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 处理人脸注册
  const handleRegisterFace = async () => {
    if (!faceImage) {
      message.error('请先拍照');
      return;
    }
    
    setLoading(true);
    try {
      // 检查token是否存在
      const token = localStorage.getItem('token');
      if (!token) {
        message.error('登录状态已失效，请重新登录');
        setTimeout(() => {
          window.location.href = '/login';
        }, 1500);
        return;
      }
      
      console.log('开始注册人脸，图片长度:', faceImage.length);
      const response = await authAPI.updateFace(faceImage);
      console.log('人脸注册响应:', response);
      
      message.success('人脸注册成功');
      setModalVisible(false);
      
      // 直接更新本地状态，避免触发额外的API请求
      setFaceRegistered(true);
      
      // 如果用户信息存在，手动更新Redux状态
      if (user) {
        // 创建更新后的用户对象
        const updatedUser = { ...user, has_face: true };
        
        // 更新本地存储
        try {
          localStorage.setItem('user', JSON.stringify(updatedUser));
        } catch (err) {
          console.error('更新本地存储失败:', err);
        }
        
        // 使用Redux action直接更新状态，而不是发起新的API请求
        dispatch({
          type: 'auth/getUserInfo/fulfilled',
          payload: updatedUser
        });
      }
    } catch (error) {
      console.error('人脸注册失败详情:', error);
      
      // 处理不同类型的错误
      if (error.response && error.response.status === 401) {
        message.error('登录已过期，请重新登录');
        setTimeout(() => {
          window.location.href = '/login';
        }, 1500);
      } else if (error.response && error.response.data) {
        message.error(`人脸注册失败: ${error.response.data.message || error.response.data.error || '服务器错误'}`);
      } else {
        message.error('人脸注册失败: ' + (error.message || '未知错误'));
      }
    } finally {
      setLoading(false);
    }
  };
  
  // 处理拍照
  const handleCapture = (imgSrc) => {
    setFaceImage(imgSrc);
  };
  
  // 如果有错误，显示错误信息
  if (error) {
    return (
      <div className="dashboard-container">
        <Typography>
          <Title level={2}>学生仪表盘</Title>
          <Paragraph type="danger">{error}</Paragraph>
          <Button type="primary" onClick={() => {
            dataFetched.current = false;
            fetchData();
          }}>
            刷新页面
          </Button>
        </Typography>
      </div>
    );
  }
  
  return (
    <div className="dashboard-container">
      <Typography>
        <Title level={2}>学生仪表盘</Title>
        <Paragraph>欢迎回来，{user?.name || '同学'}！</Paragraph>
      </Typography>
      
      {/* 个人信息卡片 */}
      <Card className="info-card" loading={loading}>
        <Row gutter={16} align="middle">
          <Col span={8}>
            <div className="avatar-container">
              <UserOutlined className="avatar-icon" />
            </div>
          </Col>
          <Col span={16}>
            <Title level={4}>{user?.name || '未知'}</Title>
            <Paragraph>学号: {user?.student_id || '未知'}</Paragraph>
            <Paragraph>班级: {user?.class_name || '未知'}</Paragraph>
            <Paragraph>
              人脸识别: {faceRegistered ? 
                <span className="face-registered"><CheckCircleOutlined /> 已注册</span> : 
                <span className="face-not-registered">未注册</span>
              }
            </Paragraph>
            
            {!faceRegistered && (
              <Button 
                type="primary" 
                icon={<CameraOutlined />} 
                onClick={() => setModalVisible(true)}
              >
                注册人脸
              </Button>
            )}
            
            {faceRegistered && (
              <Button
                type="default"
                icon={<CameraOutlined />}
                onClick={() => setModalVisible(true)}
              >
                更新人脸
              </Button>
            )}
          </Col>
        </Row>
      </Card>
      
      {/* 统计数据 */}
      <Row gutter={16} className="stats-row">
        <Col span={8}>
          <Card>
            <Statistic 
              title="总签到任务" 
              value={stats.totalTasks} 
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic 
              title="已完成签到" 
              value={stats.completedTasks} 
              valueStyle={{ color: '#3f8600' }}
              prefix={<CheckCircleOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic 
              title="待完成签到" 
              value={stats.pendingTasks}
              valueStyle={{ color: '#fa8c16' }}
              prefix={<ClockCircleOutlined />}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>
      
      {/* 人脸注册模态框 */}
      <Modal
        title="人脸注册"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="back" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button 
            key="submit" 
            type="primary" 
            loading={loading}
            disabled={!faceImage} 
            onClick={handleRegisterFace}
          >
            {faceRegistered ? '更新人脸' : '注册人脸'}
          </Button>,
        ]}
        width={520}
      >
        <div className="face-capture-container">
          <FaceCapture onCapture={handleCapture} />
          
          {faceImage && (
            <div className="preview-container">
              <h4>预览</h4>
              <img src={faceImage} alt="人脸预览" className="face-preview" />
            </div>
          )}
          
          <div className="face-tips">
            <h4>提示：</h4>
            <ul>
              <li>请确保光线充足，面部清晰可见</li>
              <li>请正对摄像头，不要佩戴墨镜等遮挡物</li>
              <li>请保持自然表情</li>
            </ul>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default Dashboard;